<template>
  <el-dialog
    :visible.sync="dialogVisible"
    width="603px"
    :before-close="handleClose"
    :close-on-click-modal="false">
    <span slot="title" style="color:#303753;font-size:14px;font-weight:600">{{$t('webchat.sendImg')}}</span>
    <div style="text-align: center;">
      <el-alert v-if="!loading" :title="`${$t('webchat.isSendImg')}${imgSrc.length > 1 ? ('（' + imgSrc.length + '）') : ''}`" type="warning" show-icon :closable="false"></el-alert>
      <div class="imgDiv" v-if="imgSrc.length === 1">
        <img :src="imgSrc[0].blobUrl"/>
        <div class="loading" v-if="imgSrc[0].status === 'upload'">{{ imgSrc[0].percent }}%</div>
        <div class="loading error" v-if="imgSrc[0].status === 'error'" @click="upload(imgSrc[0], 0)"><i class="el-icon-refresh-right"></i></div>
      </div>
      <draggable v-model="imgSrc" animation="150" ghostClass="dragClass" class="imgDiv" v-if="imgSrc.length > 1" filter=".notmove">
        <div class="imgContent notmove" v-for="(item,index) in imgSrc" :key="index" :class="{'notmove': item.status === 'upload'}">
          <img :src="item.blobUrl" object-fit="scale-down" width="100%"/>
          <div class="close" v-if="item.status !== 'upload'" @click="deleteImg(index)"><i style="font-size:14px" class="el-icon-close"></i></div>
          <div class="loading" v-if="item.status === 'upload'">{{ item.percent }}%</div>
          <div class="loading error" v-if="item.status === 'error'" @click="upload(item, index)"><i class="el-icon-refresh-right"></i></div>
        </div>
      </draggable>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose" size="mini">{{$t('public.cancel')}}</el-button>
      <el-button type="primary" @click="submit" id="dropPasteImgBtn" class="dropPasteImgBtn" :loading="loading" size="mini">{{$t('webchat.send')}}</el-button>
    </span>
  </el-dialog>
</template>

<script>
/**
 * 输入框粘贴拖拽图片组件
 * TODO 拖拽图片调整顺序因为发送消息时序不能控制暂时关闭（notmove）
 */
import draggable from 'vuedraggable'
import { getCurrentDate } from '@/utils/m7Utils'
import { PasteImguploadTo7moorImDomain } from '@/utils/qiniuUtils'
import * as uuid from 'uuid'
const imgList = ['png', 'jpg', 'gif', 'jpeg', 'bmp'] // 支持的图片类型
export default {
  props: ['webchatInfo', 'webchatData'],
  components: {
    draggable
  },
  data () {
    return {
      imgSrc: [],
      dialogVisible: false,
      imgIndex: 0,
      maxSize: 10, // 图片最大大小
      loading: false,
      uploadList: [] // 保存上传实例，取消后进行销毁
    }
  },
  watch: {
    webchatInfo: {
      handler: function (val) {
        if (['wxmini', 'weixin'].includes(val.platform)) { // 微信小程序和微信渠道
          this.maxSize = 2
        } else {
          this.maxSize = 10
        }
      },
      immediate: true
    }
  },
  mounted () {
    this.addPasteEvent()
  },
  // 修复切换tab或页面绑定事件失效bug
  activated () {
    this.addPasteEvent()
  },
  destoryed () {
    this.removePasteEvent()
  },
  methods: {
    handleClose () {
      // 销毁上传实例
      this.uploadList.forEach(uploader => {
        uploader &&
        uploader.destroy &&
        uploader.destroy()
      })
      this.imgSrc = []
      this.dialogVisible = false
      this.loading = false
      this.firstError = true
    },
     deleteImg (index) {
      this.imgSrc.splice(index, 1)
    },

    // 上传图片 status(upload:上传中,error:上传失败,ok:上传完成)
    upload (item, index) {
      this.$set(this.imgSrc[index], 'status', 'upload')
      const that = this
      let fileUploaded = (up) => {
        if (this.imgSrc.length === 0) return
        let domain = that.$store.state.isUseQiniu ? that.$store.state.fileDomain.qiniu7moorImDomain : that.$store.state.fileDomain.cos7moorImDomain
        let sourceLink = domain + (that.$store.state.isUseQiniu ? up.key : up.fileKey)
        this.$set(this.imgSrc[index], 'url', sourceLink)
        this.$set(this.imgSrc[index], 'status', 'ok')
        this.sendMsg()
        let textDom = document.getElementById('textareaContent')
        if (textDom) {
          textDom.blur()
        }
      }
      let key = () => {
        let date = getCurrentDate()
        let time = new Date().getTime()
        return 'im/' + this.webchatData.accessId + '/' + date + '/' + time + '/' + uuid.v1() + item.ext
      }
      let uploadProgress = (up, file) => {
        if (this.imgSrc.length === 0) return
        this.$set(this.imgSrc[index], 'percent', Math.floor(up.total.percent))
      }
      let error = (up, err, errTip) => {
        if (this.imgSrc.length === 0) return
        this.$set(this.imgSrc[index], 'status', 'error')
        this.$set(this.imgSrc[index], 'percent', 0)
        this.sendMsg()
      }
      const upload = PasteImguploadTo7moorImDomain(this.$store.state.session.user._id, 'dropPasteImgBtn', item.blob, item.blob.name, uploadProgress, fileUploaded, key(), error)
      this.uploadList.push(upload)
    },

    // 发送消息
    submit () {
      this.loading = true
      this.imgSrc.forEach(async (v, index) => {
        this.upload(v, index)
      })
    },

    // 轮询图片是否上传完成
    sendMsg () {
      if (this.imgSrc.some(v => v.status === 'upload')) {
        return
      }
      if (this.firstError && this.imgSrc.some(v => v.status === 'error')) {
        this.firstError = false
        this.loading = false
        return
      }
      if (!this.dialogVisible) return
      this.imgSrc.forEach(v => {
        if (v.status === 'ok') {
          this.$parent.handleSubmit({}, 'image', v.url)
          URL.revokeObjectURL(v.blobUrl)
        }
      })
      this.handleClose()
    },
    addPasteEvent () {
      if (document.getElementById('textareaContent')) {
        document.getElementById('textareaContent').addEventListener('drop', this.dropFunction)
        document.getElementById('textareaContent').addEventListener('paste', this.pasteFunction)
      }
    },
    removePasteEvent () {
      if (document.getElementById('textareaContent')) {
        document.getElementById('textareaContent').removeEventListener('drop', this.dropFunction)
        document.getElementById('textareaContent').removeEventListener('paste', this.pasteFunction)
      }
    },

    // 粘贴剪切事件
    pasteFunction (event) {
      this.imgSrc = []
      const items = (event.clipboardData || event.originalEvent.clipboardData).items;
      [...items].map(v => {
        const type = v.type.split('/').pop()
        if (v.kind === 'file' && imgList.includes(type)) {
          if (this.imgSrc.length > 9) return
          const blob = v.getAsFile()
          if (blob.size > this.maxSize * 1024 * 1024) {
            return false
          }
          const url = URL.createObjectURL(blob)
          this.imgSrc.push({
            ext: type,
            blob,
            blobUrl: url,
            percent: 0,
            url: '',
            status: ''
          })
          this.dialogVisible = true
        }
      })
      if (this.dialogVisible) {
        return false
      }
    },

    // 拖拽图片事件 使用blobUrl可以快速展示图片，不需要上传获取链接
    dropFunction (event) {
      event.preventDefault()
      this.imgSrc = []
      const items = [...event.dataTransfer.files]
      const list = []
      items.forEach(v => {
        const fileName = v.name
        const size = v.size / 1024 / 1024
        const ext = fileName.split('.').pop().toLowerCase()
        if (imgList.includes(ext)) {
          if (size <= this.maxSize) {
            if (list.length > 9) return
            list.push({ file: v, size, ext })
          }
        }
      })
      if (list.length > 0) {
        list.map(v => {
          const reader = new FileReader()
          reader.readAsDataURL(v.file)
          reader.onload = () => {
            this.imgSrc.push({
              blob: v.file,
              blobUrl: reader.result,
              percent: 0,
              url: '',
              status: '',
              ext: v.ext
            })
          }
        })
        this.dialogVisible = true
      }
    }
  }

}
</script>
<style lang="stylus" scoped>
.progressDiv
  height: 15px
  margin-top: -8px
.imgDiv
  max-width 100%
  height 345px
  margin-top 16px
  position relative
  overflow: auto
  .loading
    width: 100%
    height: 100%
    position: absolute
    top 0px
    left 0px
    text-align: center
    color #fff
    font-size: 14px
    background: rgba(0,0,0,.3)
    line-height: 400px
  .dragClass
    opacity 0
  img
    height: 100%;
    width: 100%;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    object-fit: scale-down;
  .imgContent
    width: 100px
    height: 100px
    float: left
    margin: 0px 11px 11px 0px
    position: relative
    border: 1px solid #EDEDED
    border-radius: 4px
    cursor pointer
    position: relative
    .loading
      width: 100%
      height: 100%
      position: absolute
      top 0px
      left 0px
      text-align: center
      color #fff
      font-size: 14px
      background: rgba(0,0,0,.3)
      line-height: 100px
    .error
      background: rgba(255,0,0,.2)
    .close
      position: absolute
      width: 12px
      height: 13px
      right: 2px
      top 2px
      color red
      cursor pointer
      display none
  .imgContent:nth-of-type(5n)
    margin-right: 0px
  .imgContent:hover
    .close
      display: block
</style>
